package com.jd.mysql.mgr.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.jd.mysql.mgr.pojo.MgrAccount;
import com.jd.mysql.mgr.service.IMgrAccountService;
import com.jd.mysql.mgr.util.MD5Util;
import com.jd.mysql.mgr.util.StringUtil;



public class LoginController implements Controller{
	
	public IMgrAccountService mgrAccountService;
	

	public void setMgrAccountService(IMgrAccountService mgrAccountService) {
		this.mgrAccountService = mgrAccountService;
	}



	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String ip = request.getRemoteAddr();
		Boolean loginSuccess = false;
		if(!StringUtil.isNull(password)){
			password = MD5Util.getMD5(password);
		}
		MgrAccount mgra = null;
		try{
			mgra = mgrAccountService.findMgrAccountByUsernameAndPassword(username, password);	
		}catch(Exception e){
			e.printStackTrace();
		}
		if(mgra==null){
			loginSuccess = false;
		}else{
			mgra.setLastLoginDate(new Date());
			mgra.setLastLoginIp(ip);
			mgrAccountService.updateMgrAccount(mgra);
			loginSuccess = true;
		}
		if(loginSuccess){
			request.setAttribute("msg", "Hi "+username+",welcome to 360buy.com database management system!");
			HttpSession session = request.getSession(true);
			session.setAttribute("userName", username);
			
			String groupname = mgra.getMgrAccountGroup().getMgrGroupName();
			session.setAttribute("groupname", mgra.getMgrAccountGroup().getMgrGroupName());
			session.setAttribute("group", "all".equals(groupname)?-1:mgra.getMgrAccountGroup().getId());
	        return new ModelAndView("welcome");
		}else{
			request.setAttribute("msg", "error user name!");
	        return new ModelAndView("error");
		}
	}

}
